import { ref, reactive } from 'vue'
import { useBlueTooth } from '@/store/modules/bluetooth';

export const useBlueTooths = () => {
    const blueTooth = useBlueTooth()
    const BLEInformation = reactive({
        serviceId: 0,
        writeCharacter: false,
        readCharacter: false,
        notifyCharacter: false,
        services: '',
    })

    const blueToothList = ref([] as any)
    const services = ref([] as any)
    // 封装uniapp的api
    const uniAsyncPromise = (name: string, options?: any): Promise<any> => {
        const uniApi: any = uni
        return new Promise((resolve, reject) => {
            uniApi[name]({
                ...options,
                success: function (res: any) {
                    resolve(res)
                },
                fail: function (res: any) {
                    reject(res)
                },
            })
        })
    }

    const startSearch = () => {
        uniAsyncPromise('openBluetoothAdapter').then(() => {
            uniAsyncPromise('getBluetoothAdapterState').then((res: any) => {
                // 蓝牙适配器是否可用
                if (res.available) {
                    // 蓝牙适配器是否可用
                    if (res.available) {
                        // 是否正在搜索设备
                        if (res.discovering)
                            return uni.showToast({ title: '正在搜索附近打印机设备', icon: 'none' })
                        //获取蓝牙设备信息
                        getBluetoothDevices()
                    } else uni.showModal({ title: '提示', content: '本机蓝牙不可用' })
                }
            })
        })
    }

    const getBluetoothDevices = async () => {
        try {
            await startBluetoothDeviceDiscovery();
            await wait(4000);
            await fillBluetoothDevices();
        } catch (e) {
            console.log("getBluetoothDevices Error:", e);
        }
        finally {
            await stopBluetoothDeviceDiscovery();
            await uni.hideLoading()
        }
    };

    // 开始搜索蓝牙设备
    const startBluetoothDeviceDiscovery = async () => {
        uni.showLoading({ title: '扫描中' })
        await new Promise((resolve, reject) => {
            uni.startBluetoothDevicesDiscovery({
                success: resolve,
                fail: reject,
            });
        });
        plus.bluetooth.onBluetoothDeviceFound(onBluetoothDeviceFound);
    };

    // 监听蓝牙设备
    const onBluetoothDeviceFound = (result: any) => {
        const arr = blueToothList.value;
        const devices: any[] = [];
        const listArr = result.devices;
        for (let i = 0; i < listArr.length; ++i) {
            if (listArr[i].name && listArr[i].name !== "未知设备") {
                const arrNew = arr.filter(
                    (item: any) => item.deviceId === listArr[i].deviceId
                );
                if (arrNew.length === 0) devices.push(listArr[i]);
            }
        }
        blueToothList.value = arr.concat(devices);
        console.log('onBluetoothDeviceFound', blueToothList.value);

    };

    // 填充蓝牙设备列表
    const fillBluetoothDevices = async () => {
        await new Promise((resolve: Function) => {
            plus.bluetooth.getBluetoothDevices({
                success: (res: any) => {
                    const devices: any[] = [];
                    const listArr = res.devices;
                    for (let i = 0; i < listArr.length; ++i) {
                        if (listArr[i].name && listArr[i].name !== "未知设备") {
                            devices.push(listArr[i]);
                        }
                    }
                    blueToothList.value = devices
                    console.log("fillBluetoothDevices:", blueToothList.value);
                    resolve();
                },
            });
        });
    };

    // 等待
    const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

    const chooseBluetooth = (deviceId: string) => {
        let BLEInformation = blueTooth.BLEInformation
        stopBluetoothDeviceDiscovery()

        BLEInformation.serviceId = 0
        BLEInformation.writeCharacter = false
        BLEInformation.readCharacter = false
        BLEInformation.notifyCharacter = false

        uni.showLoading({ title: '正在连接' })
        plus.bluetooth.createBLEConnection({
            deviceId,
            success(res: any) {
                console.log('createBLEConnection success:', res);
                BLEInformation.deviceId = deviceId;
                blueTooth.$patch({
                    BLEInformation
                })
                uni.hideLoading()
                setTimeout(() => {
                    getSeviceId();
                });
            },
            fail(e) {
                errorCodeTip(e.errCode);
                uni.hideLoading();
            }
        })
    }

    const getSeviceId = async () => {
        const { deviceId } = blueTooth.BLEInformation;
        console.log('BLEInformation.deviceId:', deviceId);

        // 等待1.5秒后获取蓝牙设备服务信息
        await new Promise(resolve => setTimeout(resolve, 1500));

        // 获取蓝牙设备服务信息并更新服务列表
        const { services: s } = await new Promise((resolve, reject) => {
            plus.bluetooth.getBLEDeviceServices({
                deviceId,
                success: resolve,
                fail: reject,
            });
        });
        services.value = s;
        getCharacteristics();
    }

    const getCharacteristics = async () => {
        const num = BLEInformation.serviceId
        const { deviceId } = blueTooth.BLEInformation;

        // 获取蓝牙设备特征值信息
        const { characteristics } = await new Promise((resolve, reject) => {
            plus.bluetooth.getBLEDeviceCharacteristics({
                deviceId,
                serviceId: services.value[num].uuid,
                success: resolve,
                fail: reject,
            });
        });

        // 遍历特征值列表，获取写、读、通知特征值ID和服务ID
        for (let i = 0; i < characteristics.length; i++) {
            const { uuid, properties } = characteristics[i];
            // console.log(uuid, properties, 'characteristics[i]');
            if (!BLEInformation.notifyCharacter && properties.notify) {
                blueTooth.BLEInformation.notifyCharaterId = uuid;
                blueTooth.BLEInformation.notifyServiceId = services.value[num].uuid;
                blueTooth.$patch({
                    BLEInformation: blueTooth.BLEInformation
                })
                BLEInformation.notifyCharacter = true;
            }
            if (!BLEInformation.writeCharacter && properties.write) {
                blueTooth.BLEInformation.writeCharaterId = uuid;
                blueTooth.BLEInformation.writeServiceId = services.value[num].uuid;
                blueTooth.$patch({
                    BLEInformation: blueTooth.BLEInformation
                })
                BLEInformation.writeCharacter = true;
            }
            if (!BLEInformation.readCharacter && properties.read) {
                blueTooth.BLEInformation.readCharaterId = uuid;
                blueTooth.BLEInformation.readServiceId = services.value[num].uuid;
                blueTooth.$patch({
                    BLEInformation: blueTooth.BLEInformation
                })
                BLEInformation.readCharacter = true;
            }
        }

        // 如果找不到对应的写、读、通知特征值，则继续查找下一个服务的特征值
        if (!BLEInformation.writeCharacter ||
            !BLEInformation.notifyCharacter ||
            !BLEInformation.readCharacter) {
            BLEInformation.serviceId = num + 1;
            if (num === services.length - 1) {
                console.log('找不到该读写的特征值');
                uni.showModal({
                    title: '提示',
                    content: '找不到该读写的特征值',
                });
            } else {
                await getCharacteristics();
            }
        } else openControl();
    }

    const openControl = () => {
        uni.navigateBack({ delta: 1 })
    }


    const stopBluetoothDeviceDiscovery = (deviceId?: string) => {
        const options = {
            success: (res: any) => {
                console.log('stop:', res);
            },
            fail: (e: any) => {
                console.log('stop:', e);
                errorCodeTip(e.errCode);
            },
        } as any;

        if (deviceId) {
            options.deviceId = deviceId;
        }
        uni.stopBluetoothDevicesDiscovery(options);
    };

    // 错误码提示
    const errorCodeTip = (code: number) => {
        const errorTips: any = {
            0: "正常",
            10000: "未初始化蓝牙适配器",
            10001: "当前蓝牙适配器不可用",
            10002: "没有找到指定设备",
            10003: "连接失败",
            10004: "没有找到指定服务",
            10005: "没有找到指定特征值",
            10006: "当前连接已断开",
            10007: "当前特征值不支持此操作",
            10008: "其余所有系统上报的异常",
            10009: "Android 系统特有，系统版本低于 4.3 不支持 BLE"
        }
        if (errorTips[code]) {
            uni.showToast({
                title: errorTips[code],
                icon: 'none',
            });
        }
    }
    return {
        blueToothList,
        startSearch,
        chooseBluetooth,
        uniAsyncPromise,
        stopBluetoothDeviceDiscovery
    }
}


